package com.alibaba.cirtus.ots.application.adapter.ability.facade.serviceV2.dp;

import com.alibaba.cirtus.ots.application.adapter.ability.model.features.ScItemFeatures;
import com.alibaba.cirtus.ots.application.adapter.ability.model.request.ScItemFeatureUpdateDTO;
import com.alibaba.cirtus.ots.application.adapter.ability.model.request.ScItemPublishDTO;
import com.alibaba.cirtus.ots.application.adapter.ability.model.sdo.MnScItemInfoSDO;
import com.alibaba.cirtus.ots.application.adapter.ability.utils.DubboResult;
import com.alibaba.cirtus.ots.application.adapter.ability.utils.ResultUtils;
import com.alibaba.citrus.ots.common.annotation.ProcessInvoker;
import com.alibaba.cz.base.model.brand.BrandSDO;
import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.fastjson.JSON;
import com.alibaba.lattice2.epoch.middleware.cache.runtime.service.EpochCacheService;
import com.alibaba.lattice2.epoch.sdk.model.Result;
import com.epoch.app.bcorder.model.dto.*;
import com.epoch.app.bcorder.service.BaseDataService;
import com.epoch.app.bcorder.service.BcOrderService;
import com.epoch.app.crplatformenhance.domain.scitemgroup.dto.CreateScItemGroupResponse;
import com.epoch.app.crplatformenhance.domain.scitemgroup.dto.LoadScItemGroupListRequest;
import com.epoch.app.crplatformenhance.domain.scitemgroup.dto.UpdateScItemGroupResponse;
import com.epoch.app.crplatformenhance.domain.scitemgroup.model.ScItemGroup;
import com.epoch.app.crplatformenhance.domain.scitemgroup.service.ScItemGroupService;
import com.epoch.app.crplatformenhance.domain.scitemunit.dto.ScItemUnitLoadListRequest;
import com.epoch.app.crplatformenhance.domain.scitemunit.model.ScItemUnit;
import com.epoch.app.crplatformenhance.domain.scitemunit.service.ScItemUnitService;
import com.epoch.app.crplatformenhance.model.dto.ScItemSDO;
import com.epoch.app.otsapplicationadaptersdk.contants.OtsApplicationAdapterSdkConstants;
import com.epoch.app.otsapplicationadaptersdk.dp.DpProduct;
import com.epoch.app.otsapplicationadaptersdk.dp.MnDataProductResponse;
import com.epoch.app.otsapplicationadaptersdk.dp.MnDataProductSDO;
import com.epoch.app.otsapplicationadaptersdk.mnproductdata.dto.DoProductHandlerRequest;
import com.epoch.app.otsapplicationadaptersdk.mnproductdata.dto.DoProductUnitConversionHandlerRequest;
import com.epoch.app.otsapplicationadaptersdk.mnproductdata.service.MnProductDataService;
import com.epoch.app.otsapplicationadaptersdk.model.dto.YwztRestDpProductDataRequest;
import com.epoch.app.otsapplicationadaptersdk.service.DpService;
import com.google.common.base.Throwables;
import com.google.common.collect.Lists;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

/**
 * @author zls
 * @description: 货品数据同步 + 业态 （除去常温）
 */
@Component
public class MnProductDataServiceImpl implements MnProductDataService {
    private final Log log = Log.getLogger(MnProductDataServiceImpl.class);
    // 低温产品组编码
    private final static String LOW_TEMPERATURE_CODE = "12";

    @Resource
    private BaseDataService baseDataService;

    @Resource
    private ScItemGroupService scItemGroupService;

    @Resource
    private ScItemUnitService scItemUnitService;

    @Resource
    private DpService dpService;

    @Resource
    private MnProductUnitDataService mnProductUnitDataService;

    @ProcessInvoker(remark = "MnProductDataService", errorCode = "OTS-02-007-00-16-999", printLog = true)
    @Override
    public Object doProductHandler(DoProductHandlerRequest doHandlerRequest) {
        // 1、构造中台查询参数
        YwztRestDpProductDataRequest param = buildMnQueryMap(doHandlerRequest);
        //调用中台接口获取货品数据（分页信息）
        MnDataProductSDO mnDataProductSDO = getResultListMap(param);
        if (mnDataProductSDO == null) {
            return mnDataProductSDO;
        }
        Integer totalNum = mnDataProductSDO.getTotalNum();
        Integer pageSize = mnDataProductSDO.getPageSize();
        int pageTotalNum = totalNum / pageSize;
        int remainder = totalNum % pageSize;
        if (remainder != 0) {
            pageTotalNum = pageTotalNum + 1;
        }
        log.info("MnProductDataServiceImpl_pageTotalNum={}", pageTotalNum);
        // 分页同步货品主数据
        for (int i = 1; i <= pageTotalNum; i++) {
            param.setPageNum(String.valueOf(i));
            log.info("MnProductDataServiceImpl_doProductHandler_request={}", JSON.toJSONString(param));
            MnDataProductSDO dataProductSDO = getResultListMap(param);
            log.info("MnProductDataServiceImpl_doProductHandler_result={}", JSON.toJSONString(dataProductSDO));

            List<DpProduct> mnScItemInfoList = convertToMnScItemInfo(dataProductSDO);
            if (CollectionUtils.isEmpty(mnScItemInfoList)) {
                log.info("MnProductDataServiceImpl_doProductHandler_mnScItemInfoList is empty");
                continue;
            }
            log.info("MnProductDataServiceImpl_doProductHandler_syncCurrentPageOfScItemInfo start---");

            // 同步
            syncCurrentPageOfScItemInfo(mnScItemInfoList);
        }
        return mnDataProductSDO;
    }

    @ProcessInvoker(remark = "MnProductDataService", errorCode = "OTS-02-007-00-16-999", printLog = true)
    @Override
    public Object doProductUnitConversionHandler(DoProductUnitConversionHandlerRequest request) {
        log.info("MnProductDataServiceImpl_doProductUnitConversionHandler:{}", JSON.toJSONString(request));
        return mnProductUnitDataService.doHandler(request);
    }

    /**
     * 构造查询参数
     *
     * @return
     */
    private YwztRestDpProductDataRequest buildMnQueryMap(DoProductHandlerRequest doHandlerRequest) {
        String ds = doHandlerRequest.getDs();
        YwztRestDpProductDataRequest restDpProductDataRequest = YwztRestDpProductDataRequest.builder()
                .fromSys(doHandlerRequest.getFromSys())
                .pageNum(doHandlerRequest.getPageNum())
                .pageSize(doHandlerRequest.getPageSize())
                .build();
        if (StringUtils.isNotBlank(ds)) {
            restDpProductDataRequest.setDs(ds);
        }
        return restDpProductDataRequest;
    }

    /**
     * 获取蒙牛货品数据
     *
     * @param param
     * @return
     */
    private MnDataProductSDO getResultListMap(YwztRestDpProductDataRequest param) {
        log.info("param{}", param);

        MnDataProductResponse mnDataProductResponse = null;
        int retryTimes = 0;
        String errCode = null;
        do {
            if (ErrorCodeConstant.RATE_LIMIT.equals(errCode)) {
                try {
                    Thread.sleep(120000);
                } catch (InterruptedException e) {
                    log.error("MnDataIf001ServiceImpl#doHandler InterruptedException", e);
                }
            }
            mnDataProductResponse = dpService.ywztRestDpProductData(param);
            errCode = mnDataProductResponse.getErrCode();
        } while (!"0".equals(errCode) && retryTimes++ < 10);
        MnDataProductSDO data = mnDataProductResponse.getData();
        if (data == null) {
            return null;
        }
        return data;
    }

    /**
     * mapToObject
     *
     * @param mnDataProductSDO
     * @return
     */
    private List<DpProduct> convertToMnScItemInfo(MnDataProductSDO mnDataProductSDO) {
        List<DpProduct> dpScItemInfoList = mnDataProductSDO.getRows();
        return dpScItemInfoList;
    }

    private void syncCurrentPageOfScItemInfo(List<DpProduct> dpScItemInfoList) {
        for (DpProduct dpProduct : dpScItemInfoList) {
            // 数据转换
            MnScItemInfoSDO mnScItemInfoSDO = convertToMnScItemInfoSDO(dpProduct);
            // 过滤常温业态数据
            if (filterBusinessType(mnScItemInfoSDO.getScItemGroupCode())){
                log.info("MnProductDataServiceImpl_syncCurrentPageOfScItemInfo_filterConstantTemperature:{}", JSON.toJSONString(dpProduct));
                continue;
            }

            try {
                log.info("MnProductDataServiceImpl_syncCurrentPageOfScItemInfo_saveBrand start");
                // 一  同步品牌
                String brandId = saveBrand(mnScItemInfoSDO);
                log.info("MnProductDataServiceImpl_syncCurrentPageOfScItemInfo_saveBrand end_brandId:{}", brandId);
                log.info("MnProductDataServiceImpl_syncCurrentPageOfScItemInfo_saveScItemGroup start");
                // 二、同步货品组
                String scItemGroupId = saveScItemGroup(mnScItemInfoSDO);
                log.info("MnProductDataServiceImpl_syncCurrentPageOfScItemInfo_saveScItemGroup end_scItemGroupId:{}", scItemGroupId);
                // 三、同步货品
                saveScItem(mnScItemInfoSDO, brandId, scItemGroupId);
                log.info("MnProductDataServiceImpl_syncCurrentPageOfScItemInfo_saveScItem end");

            } catch (Exception e) {
                log.error("MnProductDataServiceImpl_syncCurrentPageOfScItemInfo_fail_error：{}, mnScItemInfoSDO:{}", Throwables.getStackTraceAsString(e), JSON.toJSONString(mnScItemInfoSDO));
            }
        }
    }

    /**
     * 根据业态编码过滤数据
     * 常温编码：11
     * @return true-需要过滤， false-不需要过滤
     */
    private boolean filterBusinessType(String scItemGroupCode){
        if (StringUtils.isBlank(scItemGroupCode)){
            return true;
        }
        List<String> filter = new ArrayList<>();
        if (StringUtils.isBlank(OtsApplicationAdapterSdkConstants.YWZT_ITEM_BUSINESS_TYPE())) {
            filter.add(LOW_TEMPERATURE_CODE);
        } else {
            String[] split = OtsApplicationAdapterSdkConstants.YWZT_ITEM_BUSINESS_TYPE().split(",");
            filter = Arrays.asList(split);
        }
        log.info("MnProductDataServiceImpl_filterBusinessType:{}, scItemGroupCode:{}", JSON.toJSONString(filter), scItemGroupCode);
        if (filter.contains(scItemGroupCode)){
            return false;
        }
        return true;
    }

    /**
     * 货品主数据转换
     *
     * @param dpProduct
     * @return mnScItemInfoSDO
     */
    private MnScItemInfoSDO convertToMnScItemInfoSDO(DpProduct dpProduct) {
        MnScItemInfoSDO mnScItemInfoSDO = new MnScItemInfoSDO();
        mnScItemInfoSDO.setOutId(StringUtils.isBlank(dpProduct.getMatnr()) ? "" : dpProduct.getMatnr().trim().trim());
        String grossWeight = "0";
        if (StringUtils.isNotBlank(dpProduct.getBrgew())) {
            String grossWeightStr = dpProduct.getBrgew().trim();
            Double grossWeightStrDouble = Double.valueOf(grossWeightStr);
            grossWeight = new BigDecimal(grossWeightStrDouble).multiply(new BigDecimal(1000)).setScale(0, BigDecimal.ROUND_UP).toString();
        }
        mnScItemInfoSDO.setGrossWeight(grossWeight);
        mnScItemInfoSDO.setWeightUnit(StringUtils.isBlank(dpProduct.getGewei()) ? "" : dpProduct.getGewei().trim());
        // 长宽高，毛重，净重，去小数处理，其中长宽高直接去小数（数据的小数都是000，毛重、净重乘以1000，查询的时候除以1000）
        String length = "0";
        if (StringUtils.isNotBlank(dpProduct.getLaeng())) {
            String lengthStr = dpProduct.getLaeng().trim();
            length = String.valueOf(Double.valueOf(lengthStr).intValue());
        }
        mnScItemInfoSDO.setLength(length);
        String width = "0";
        if (StringUtils.isNotBlank(dpProduct.getBreit())) {
            String widthStr = dpProduct.getBreit().trim();
            width = String.valueOf(Double.valueOf(widthStr).intValue());
        }
        mnScItemInfoSDO.setWidth(width);
        String height = "0";
        if (StringUtils.isNotBlank(dpProduct.getHoehe())) {
            String heightStr = dpProduct.getHoehe().trim();
            height = String.valueOf(Double.valueOf(heightStr).intValue());
        }
        mnScItemInfoSDO.setHeight(height);
        mnScItemInfoSDO.setMaterialDesc(StringUtils.isBlank(dpProduct.getMaktx()) ? "" : dpProduct.getMaktx().trim());
        mnScItemInfoSDO.setMaterialGroupCode(StringUtils.isBlank(dpProduct.getMatkl()) ? "" : dpProduct.getMatkl().trim());
        mnScItemInfoSDO.setIndustryField(StringUtils.isBlank(dpProduct.getMbrsh()) ? "" : dpProduct.getMbrsh().trim());
        // 单位"件"的编码从ST改成PC  TODO
        String unitCode = "";
        if (!StringUtils.isBlank(dpProduct.getMeins())) {
            unitCode = dpProduct.getMeins().trim();
            if ("ST".equals(unitCode)) {
                unitCode = "PC";
            }
        }
        // unitName实际存单位编码
        // unit 和unitNameDesc是单位名称
        mnScItemInfoSDO.setUnitName(unitCode);
        // 存在某些货品数据（例如：奶卡套餐...,有单位编码，没单位名称的情况，这是客户数据本身的问题，此类货品根据单位编码查名称，暂定这样）
        String unitNameDesc = "";
        if (StringUtils.isBlank(dpProduct.getMeinsdesc())) {
            if (StringUtils.isNotBlank(mnScItemInfoSDO.getUnitName())) {
                ScItemUnitLoadListRequest scItemUnitLoadListRequest = new ScItemUnitLoadListRequest();
                scItemUnitLoadListRequest.setCode(mnScItemInfoSDO.getUnitName());
                Result<List<ScItemUnit>> loadScItemUnitResult = scItemUnitService.loadScItemUnitList(scItemUnitLoadListRequest);
                List<ScItemUnit> scItemUnitList = loadScItemUnitResult.getResult();
                if (CollectionUtils.isNotEmpty(scItemUnitList)) {
                    ScItemUnit scItemUnit = scItemUnitList.get(0);
                    unitNameDesc = scItemUnit.getName();
                }
            }
        } else {
            unitNameDesc = dpProduct.getMeinsdesc().trim();
        }
        mnScItemInfoSDO.setUnitNameDesc(unitNameDesc);
        mnScItemInfoSDO.setUnit(unitNameDesc);
        mnScItemInfoSDO.setGuaranteePeriod(StringUtils.isBlank(dpProduct.getMhdhb()) ? "" : dpProduct.getMhdhb().trim());
        mnScItemInfoSDO.setMaterialType(StringUtils.isBlank(dpProduct.getMtart()) ? "" : dpProduct.getMtart().trim());
        String netWeight = "0";
        if (StringUtils.isNotBlank(dpProduct.getNtgew())) {
            String netWeightStr = dpProduct.getNtgew().trim();
            Double netWeightDouble = Double.valueOf(netWeightStr);
            netWeight = new BigDecimal(netWeightDouble).multiply(new BigDecimal(1000)).setScale(0, BigDecimal.ROUND_UP).toString();
        }
        mnScItemInfoSDO.setNetWeight(netWeight);
        mnScItemInfoSDO.setScItemGroupCode(StringUtils.isBlank(dpProduct.getSpart()) ? "" : dpProduct.getSpart().trim());
        mnScItemInfoSDO.setScItemGroupDesc(StringUtils.isBlank(dpProduct.getSpartdesc()) ? "" : dpProduct.getSpartdesc().trim());
        mnScItemInfoSDO.setMaterialGroupDesc(StringUtils.isBlank(dpProduct.getWgbez()) ? "" : dpProduct.getWgbez().trim());
        mnScItemInfoSDO.setDensity(StringUtils.isBlank(dpProduct.getZzmat007()) ? "" : dpProduct.getZzmat007().trim().trim());
        mnScItemInfoSDO.setSpecName(StringUtils.isBlank(dpProduct.getZzmat039()) ? "" : dpProduct.getZzmat039().trim());
        mnScItemInfoSDO.setFinancialBrand(StringUtils.isBlank(dpProduct.getZzmat901()) ? "" : dpProduct.getZzmat901().trim());
        mnScItemInfoSDO.setVolumeUnit(StringUtils.isBlank(dpProduct.getVoleh()) ? "" : dpProduct.getVoleh().trim());
        mnScItemInfoSDO.setStandardprice(StringUtils.isBlank(dpProduct.getZzmat102()) ? "" : dpProduct.getZzmat102().trim());
        mnScItemInfoSDO.setRetailPrice(StringUtils.isBlank(dpProduct.getZzmat103()) ? "" : dpProduct.getZzmat103().trim());
        mnScItemInfoSDO.setBrandDesc(StringUtils.isBlank(dpProduct.getBackup1()) ? "" : dpProduct.getBackup1().trim());
        mnScItemInfoSDO.setCategoryChildDesc(StringUtils.isBlank(dpProduct.getBackup2()) ? "" : dpProduct.getBackup2().trim());
        mnScItemInfoSDO.setPackDesc(StringUtils.isBlank(dpProduct.getBezei()) ? "" : dpProduct.getBezei().trim());
        mnScItemInfoSDO.setPackagingMaterial(StringUtils.isBlank(dpProduct.getMagrv()) ? "" : dpProduct.getMagrv().trim());
        mnScItemInfoSDO.setProductLevel(StringUtils.isBlank(dpProduct.getPrdha()) ? "" : dpProduct.getPrdha().trim());
        mnScItemInfoSDO.setBusinessVolume(StringUtils.isBlank(dpProduct.getVolum()) ? "" : dpProduct.getVolum().trim());
        mnScItemInfoSDO.setMinCapacity(StringUtils.isBlank(dpProduct.getZfxbz()) ? "" : dpProduct.getZfxbz().trim());
        mnScItemInfoSDO.setPackingCoefficient(StringUtils.isBlank(dpProduct.getZzmat004()) ? "" : dpProduct.getZzmat004().trim());
        mnScItemInfoSDO.setMinCapacityUnit(StringUtils.isBlank(dpProduct.getZzmat008()) ? "" : dpProduct.getZzmat008().trim());
        mnScItemInfoSDO.setProductInput(StringUtils.isBlank(dpProduct.getZzmat010()) ? "" : dpProduct.getZzmat010().trim());
        mnScItemInfoSDO.setProductType(StringUtils.isBlank(dpProduct.getZzmat011()) ? "" : dpProduct.getZzmat011().trim());
        mnScItemInfoSDO.setCategory(StringUtils.isBlank(dpProduct.getZzmat030()) ? "" : dpProduct.getZzmat030().trim());
        mnScItemInfoSDO.setCategoryDesc(StringUtils.isBlank(dpProduct.getZzmat030desc()) ? "" : dpProduct.getZzmat030desc().trim());
        mnScItemInfoSDO.setBrandCode(StringUtils.isBlank(dpProduct.getZzmat031()) ? "" : dpProduct.getZzmat031().trim());
        mnScItemInfoSDO.setBrandGroupCode(StringUtils.isBlank(dpProduct.getZzmat033()) ? "" : dpProduct.getZzmat033().trim());
        mnScItemInfoSDO.setBrandGroupDesc(StringUtils.isBlank(dpProduct.getZzmat033desc()) ? "" : dpProduct.getZzmat033desc().trim());
        mnScItemInfoSDO.setCategoryChildCode(StringUtils.isBlank(dpProduct.getZzmat034()) ? "" : dpProduct.getZzmat034().trim());
        mnScItemInfoSDO.setTaxRate(StringUtils.isBlank(dpProduct.getZzmat036()) ? "" : dpProduct.getZzmat036().trim().trim());
        mnScItemInfoSDO.setSaleTypeCode(StringUtils.isBlank(dpProduct.getZzmat043()) ? "" : dpProduct.getZzmat043().trim());
        mnScItemInfoSDO.setSaleType(StringUtils.isBlank(dpProduct.getZzmat043t()) ? "" : dpProduct.getZzmat043t().trim());
        mnScItemInfoSDO.setFinancialBrandDesc(StringUtils.isBlank(dpProduct.getZzmat901desc()) ? "" : dpProduct.getZzmat901desc().trim());
        mnScItemInfoSDO.setBarCode(StringUtils.isBlank(dpProduct.getZzmat902()) ? "" : dpProduct.getZzmat902().trim());
        mnScItemInfoSDO.setBarOutCode(StringUtils.isBlank(dpProduct.getZzmat903()) ? "" : dpProduct.getZzmat903().trim());
        mnScItemInfoSDO.setFlavor(StringUtils.isBlank(dpProduct.getZzmat025()) ? "" : dpProduct.getZzmat025().trim());
        mnScItemInfoSDO.setMaterialStatus(StringUtils.isBlank(dpProduct.getMstae()) ? "" : dpProduct.getMstae().trim());
        mnScItemInfoSDO.setDepartmentCode(StringUtils.isBlank(dpProduct.getZzmat109()) ? "" : dpProduct.getZzmat109().trim());
        mnScItemInfoSDO.setDepartmentName(StringUtils.isBlank(dpProduct.getZzmat110()) ? "" : dpProduct.getZzmat110().trim());
        return mnScItemInfoSDO;
    }

    /**
     * 保存品牌数据（品牌组在features中）
     *
     * @param mnScItemInfoSDO
     * @return
     */
    private String saveBrand(MnScItemInfoSDO mnScItemInfoSDO) {
        String brandId;
        // 1、查询品牌信息（根据名称）
        BaselineQueryBrandPageListRequest baselineQueryBrandPageListRequest = new BaselineQueryBrandPageListRequest();
        // 根据修改时间排一下  按理说只有一天
        baselineQueryBrandPageListRequest.setSortByUpdateTimeDesc(true);
        // 品牌按名称唯一匹配
        if (StringUtils.isBlank(mnScItemInfoSDO.getBrandDesc())) {
            return null;
        }
        baselineQueryBrandPageListRequest.setBrandName(mnScItemInfoSDO.getBrandDesc());
        Object queryBrandPageList = baseDataService.baselineQueryBrandPageList(baselineQueryBrandPageListRequest);
        if (queryBrandPageList == null){
            log.info("MnProductDataServiceImpl_saveBrand_baselineQueryBrandPageList, brandName:{}", mnScItemInfoSDO.getBrandDesc());
        }
        DubboResult brandQueryResult = ResultUtils.getDubboPageResult((Map) queryBrandPageList);
        Map result = (Map) brandQueryResult.getResult();
        List<Map<String, Object>> brandList = (List<Map<String, Object>>) result.get("brandSDOList");
        // 更新品牌信息
        if (CollectionUtils.isNotEmpty(brandList)) {
            Map<String, Object> brandMap = brandList.get(0);
            brandId = brandMap.get("brandId").toString();
            BaselineEditBrandRequest baselineEditBrandRequest = new BaselineEditBrandRequest();
            BrandSDO brandSDO = new BrandSDO();
            brandSDO.setBrandId(brandId);
            brandSDO.setBrandName(mnScItemInfoSDO.getBrandDesc());
            brandSDO.setBrandNameCn(mnScItemInfoSDO.getBrandDesc());
            brandSDO.setBrandType(1);
            // 品牌组信息在features中
            Map<String, String> brandFeaturesMap = new HashMap<>();
            brandFeaturesMap.put("brandGroupCode", mnScItemInfoSDO.getBrandGroupCode());
            brandFeaturesMap.put("brandGroupDesc", mnScItemInfoSDO.getBrandGroupDesc());
            brandSDO.setBrandFeatures(brandFeaturesMap);
            baselineEditBrandRequest.setBrandSDO(brandSDO);
            Object editBrand = baseDataService.baselineEditBrand(baselineEditBrandRequest);
            DubboResult brandEditResult = ResultUtils.getDubboPageResult((Map) editBrand);
            Boolean editResultSuccess = brandEditResult.getSuccess();
            if (!editResultSuccess) {
                throw new RuntimeException("更新品牌信息异常");
            }

        }
        // 新建品牌
        else {
            BaselineCreateBrandRequest baselineCreateBrandRequest = new BaselineCreateBrandRequest();
            BrandSDO brandSDO = new BrandSDO();
            brandSDO.setBrandName(mnScItemInfoSDO.getBrandDesc());
            brandSDO.setBrandNameCn(mnScItemInfoSDO.getBrandDesc());
            // 默认自有品牌
            brandSDO.setBrandType(1);
            brandSDO.setBrandCreateTime(new Date());
            // 品牌组信息在features中
            Map<String, String> brandFeaturesMap = new HashMap<>();
            brandFeaturesMap.put("brandGroupCode", mnScItemInfoSDO.getBrandGroupCode());
            brandFeaturesMap.put("brandGroupDesc", mnScItemInfoSDO.getBrandGroupDesc());
            brandSDO.setBrandFeatures(brandFeaturesMap);
            baselineCreateBrandRequest.setBrandSDO(brandSDO);
            Object createBrand = baseDataService.baselineCreateBrand(baselineCreateBrandRequest);
            DubboResult brandEditResult = ResultUtils.getDubboPageResult((Map) createBrand);
            Boolean createResultSuccess = brandEditResult.getSuccess();
            if (!createResultSuccess) {
                throw new RuntimeException("新建品牌信息异常");
            }
            Map createBrandMap = (Map) createBrand;
            Map mapResult = (Map) createBrandMap.get("result");
            Map map = (Map) mapResult.get("result");
            brandId = map.get("brandId").toString();
        }
        return brandId;
    }

    /**
     * 保存货品组数据
     *
     * @param mnScItemInfoSDO
     * @return
     */
    private String saveScItemGroup(MnScItemInfoSDO mnScItemInfoSDO) {
        String scItemGroupId;
        // 1、查询货品组
        LoadScItemGroupListRequest loadScItemGroupListRequest = new LoadScItemGroupListRequest();
        loadScItemGroupListRequest.setCode(mnScItemInfoSDO.getScItemGroupCode());
        Result<List<ScItemGroup>> scItemGroupList = scItemGroupService.loadScItemGroupList(loadScItemGroupListRequest);
        List<ScItemGroup> scItemGroupListResult = scItemGroupList.getResult();
        // 编辑货品组
        if (CollectionUtils.isNotEmpty(scItemGroupListResult)) {
            ScItemGroup scItemGroup = scItemGroupListResult.get(0);
            scItemGroupId = scItemGroup.getId().toString();
            ScItemGroup updateScItemGroup = new ScItemGroup();
            updateScItemGroup.setId(Long.valueOf(scItemGroupId));
            updateScItemGroup.setCode(mnScItemInfoSDO.getScItemGroupCode());
            updateScItemGroup.setOutCode(mnScItemInfoSDO.getScItemGroupCode());
            updateScItemGroup.setName(mnScItemInfoSDO.getScItemGroupDesc());
            updateScItemGroup.setUpdater("1000000001");
            updateScItemGroup.setGmtModified(new Date());
            updateScItemGroup.setStatus(1);
            UpdateScItemGroupResponse updateScItemGroupResponse = scItemGroupService.updateScItemGroup(updateScItemGroup);
            if (!(updateScItemGroupResponse.getCount() > 0)) {
                throw new RuntimeException("编辑货品组信息异常");
            }
        }
        // 新建货品组
        else {
            ScItemGroup createScItemGroup = new ScItemGroup();
            createScItemGroup.setOutCode(mnScItemInfoSDO.getScItemGroupCode());
            createScItemGroup.setCode(mnScItemInfoSDO.getScItemGroupCode());
            createScItemGroup.setName(mnScItemInfoSDO.getScItemGroupDesc());
            createScItemGroup.setGmtCreate(new Date());
            createScItemGroup.setCreator("1000000001");
            createScItemGroup.setStatus(1);
            CreateScItemGroupResponse scItemGroup = scItemGroupService.createScItemGroup(createScItemGroup);
            scItemGroupId = scItemGroup.getLastInsertId();

        }
        return scItemGroupId;
    }

    /**
     * 更新规格组名称
     * @param scItemId
     * @param newMaterialDesc
     */
    private void updateItemSpec(String scItemId,String newMaterialDesc){
        BaselineQueryRelationSpecRequest baselineQueryRelationSpecRequest = new BaselineQueryRelationSpecRequest();
        baselineQueryRelationSpecRequest.setScItemId(scItemId);
        BaselineQueryRelationSpecResponse baselineQueryRelationSpecResponse = baseDataService.baselineQueryRelationSpec(baselineQueryRelationSpecRequest);
        if (null == baselineQueryRelationSpecResponse || null == baselineQueryRelationSpecResponse.getResult()) {
            return;
        }
        Map queryResult = (Map) baselineQueryRelationSpecResponse.getResult();
        List<Map<String, Object>> scItemSpecList = (List<Map<String, Object>>) queryResult.get("scItemSpecSDOList");
        if(CollectionUtils.isNotEmpty(scItemSpecList)){
            Map<String, Object> scItemSpecMap = scItemSpecList.get(0);
            String specGroupId = (String) scItemSpecMap.get("specGroupId");
            BaselineEditItemSpecRequest baselineEditItemSpecRequest = new BaselineEditItemSpecRequest();
            baselineEditItemSpecRequest.setSpecGroupId(specGroupId);
            baselineEditItemSpecRequest.setSpecGroupName(newMaterialDesc + "规格组");
            Map editItemSpec = (Map)baseDataService.baselineEditItemSpec(baselineEditItemSpecRequest);
            log.error("MnProductDataServiceImpl_updateItemSpec_request={},result={}", JSON.toJSONString(baselineEditItemSpecRequest),JSON.toJSONString(editItemSpec));
            DubboResult editItemSpecResult = null;
            try {
                editItemSpecResult = ResultUtils.getDubboResult(editItemSpec);
            } catch (Exception e) {
                log.error("MnProductDataServiceImpl_updateItemSpec_error:", e);
                log.error("MnProductDataServiceImpl_updateItemSpec_error_specGroupId={}", specGroupId);
            }
        }
    }

    /**
     * 保存货品数据
     *
     * @param mnScItemInfoSDO
     * @return
     */
    private Boolean saveScItem(MnScItemInfoSDO mnScItemInfoSDO, String brandId, String scItemGroupId) {
        // 1、查询货品
        BaselineQueryScItemByPageRequest baselineQueryScItemByPageRequest = new BaselineQueryScItemByPageRequest();
        baselineQueryScItemByPageRequest.setOutIdList(Lists.newArrayList(mnScItemInfoSDO.getOutId()));
        Object queryScItemByPage = baseDataService.baselineQueryScItemByPage(baselineQueryScItemByPageRequest);
        DubboResult result = ResultUtils.getDubboPageResult((Map) queryScItemByPage);
        List<Map<String, Object>> scItemList = (List<Map<String, Object>>) result.getResult();
        // 2、更新货品
        if (CollectionUtils.isNotEmpty(scItemList)) {
            log.info("MnProductDataServiceImpl_saveScItem_update");
            Map<String, Object> stringObjectMap = scItemList.get(0);
            ScItemSDO scItemSDO = JSON.parseObject(JSON.toJSONString(stringObjectMap), ScItemSDO.class);
            String scItemId = scItemSDO.getScItemId();
            //更新规格组名称
            try {
                updateItemSpec(scItemId,mnScItemInfoSDO.getMaterialDesc());
            } catch (Exception e) {
            }
            // 基线的edit方法，不传会抹掉部分字段
            BaselineEditScItemRequest baselineEditScItemRequest = new BaselineEditScItemRequest();
            ScItemSDO updateScItemSDO = new ScItemSDO();
            updateScItemSDO.setScItemId(scItemId);
            updateScItemSDO.setTitle(mnScItemInfoSDO.getMaterialDesc());
            updateScItemSDO.setOuterId(mnScItemInfoSDO.getOutId());
            updateScItemSDO.setBrandId(brandId);
            updateScItemSDO.setBarCode(mnScItemInfoSDO.getBarCode());
            // 纪元接口用的入参categoryId，通过纪元映射
            updateScItemSDO.setLeafCategoryId(scItemSDO.getLeafCategoryId());
            updateScItemSDO.setType(0);
            // 这些在 features中，中台接口是全量覆盖更新接口，不传会抹掉
            updateScItemSDO.setUnit(scItemSDO.getUnit());
            updateScItemSDO.setLength(scItemSDO.getLength());
            updateScItemSDO.setWidth(scItemSDO.getWidth());
            updateScItemSDO.setHeight(scItemSDO.getHeight());
            updateScItemSDO.setGrossWeight(scItemSDO.getGrossWeight());
            updateScItemSDO.setNetWeight(scItemSDO.getNetWeight());
            baselineEditScItemRequest.setScItemEditDTO(updateScItemSDO);
            log.info("MnProductDataServiceImpl_baselineEditScItem_req:{}", JSON.toJSONString(baselineEditScItemRequest));
            Object editScItem = baseDataService.baselineEditScItem(baselineEditScItemRequest);
            log.info("MnProductDataServiceImpl_baselineEditScItem_result:{}", JSON.toJSONString(editScItem));

            // 3、启用禁用
            // 2021/11/20 物料状态有值，表示同步过来的货品数据是禁用状态 默认都是启用
            if (StringUtils.isNotBlank(mnScItemInfoSDO.getMaterialStatus())) {
                BaselineDisableScItemRequest baselineDisableScItemRequest = new BaselineDisableScItemRequest();
                baselineDisableScItemRequest.setScItemId(scItemId);
                baseDataService.baselineDisableScItem(baselineDisableScItemRequest);
            }else {
                //2023/01/12 支持货品禁用变启用
                if (scItemSDO.getStatus() == -1) {
                    BaselineEnableScItemRequest baselineEnableScItemRequest = new BaselineEnableScItemRequest();
                    baselineEnableScItemRequest.setScItemId(scItemId);
                    baseDataService.baselineEnableScItem(baselineEnableScItemRequest);
                }
            }

            // 4、更新货品features
            BaselineEditScItemFeatureRequest baselineEditScItemFeatureRequest = new BaselineEditScItemFeatureRequest();
            ScItemFeatureUpdateDTO scItemFeatureUpdateDTO = new ScItemFeatureUpdateDTO();
            scItemFeatureUpdateDTO.setScItemId(scItemId);
            Set<String> featuresKey = scItemSDO.getFeatures().keySet();
            // features中保留物料组字段，其他删除在添加（基线接口中，如果全部删除features中的key，反而不能删除）
            featuresKey.remove("materialGroupCode");
            // 货品features的实体
            ScItemFeatures scItemFeatures = new ScItemFeatures();
            BeanUtils.copyProperties(mnScItemInfoSDO, scItemFeatures);
            Map<String, String> addFeaturesMap = JSON.parseObject(JSON.toJSONString(scItemFeatures), Map.class);
            scItemFeatureUpdateDTO.setAddFeatureMap(addFeaturesMap);
            scItemFeatureUpdateDTO.setRemoveFeatureKeyList(new HashSet<>());
            List<ScItemFeatureUpdateDTO> featureUpdateList = new ArrayList<>();
            featureUpdateList.add(scItemFeatureUpdateDTO);
            baselineEditScItemFeatureRequest.setFeatureUpdateList(featureUpdateList);
            baseDataService.baselineEditScItemFeature(baselineEditScItemFeatureRequest);

        }
        // 新增货品
        else {
            log.info("MnProductDataServiceImpl_saveScItem_insert");
            ScItemPublishDTO scItemPublishDTO = new ScItemPublishDTO();
            scItemPublishDTO.setTitle(mnScItemInfoSDO.getMaterialDesc());
            scItemPublishDTO.setOuterId(mnScItemInfoSDO.getOutId());
            scItemPublishDTO.setType(0);
            scItemPublishDTO.setBrandId(brandId);
            // 同步默认商家是0
            scItemPublishDTO.setMerchantId("0");
            // 产品条码
            scItemPublishDTO.setBarCode(mnScItemInfoSDO.getBarCode());
            // 货品features的实体
            ScItemFeatures scItemFeatures = new ScItemFeatures();
            BeanUtils.copyProperties(mnScItemInfoSDO, scItemFeatures);
            Map<String, String> createScItemMap = JSON.parseObject(JSON.toJSONString(scItemFeatures), Map.class);
            createScItemMap.put("scItemGroupId", scItemGroupId);
            scItemPublishDTO.setFeatures(createScItemMap);
            BaselineCreateScItemRequest baselineCreateScItemRequest = new BaselineCreateScItemRequest();
            baselineCreateScItemRequest.setScItemPublishDTO(scItemPublishDTO);
            log.info("MnProductDataServiceImpl_baselineCreateScItem_req:{}", JSON.toJSONString(baselineCreateScItemRequest));
            Object createScItem = baseDataService.baselineCreateScItem(baselineCreateScItemRequest);
            log.info("MnProductDataServiceImpl_baselineCreateScItem_result:{}", JSON.toJSONString(createScItem));

            Map createScItemResultMap = (Map) createScItem;
            Map mapResult = (Map) createScItemResultMap.get("result");
            Boolean success = (Boolean) mapResult.get("success");
            String message = (String) mapResult.get("message");
            if(success!=null && !success){
                log.error("MnProductDataServiceImpl_syncCurrentPageOfScItemInfo_fail_mnScItemInfoSDO={},message={}", JSON.toJSONString(scItemPublishDTO),message);
                return false;
            }

            Map map = (Map) mapResult.get("result");
            String scItemId = map.get("scItemId").toString();

            // 3、启用禁用
            // 2021/11/20 物料状态有值，表示同步过来的货品数据是禁用状态 默认都是启用
            if (StringUtils.isNotBlank(mnScItemInfoSDO.getMaterialStatus())) {
                BaselineDisableScItemRequest baselineDisableScItemRequest = new BaselineDisableScItemRequest();
                baselineDisableScItemRequest.setScItemId(scItemId);
                baseDataService.baselineDisableScItem(baselineDisableScItemRequest);
            }
        }
        return true;
    }
}
